package com.xps.and.yuntong.Ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.bumptech.glide.Glide;
import com.xps.and.yuntong.Constants;
import com.xps.and.yuntong.Data.bean1.doRegister;
import com.xps.and.yuntong.Data.net.UserNetWorks;
import com.xps.and.yuntong.R;
import com.xps.and.yuntong.Utils.AppCommond;
import com.xps.and.yuntong.Utils.AssetsUitls;
import com.xps.and.yuntong.Utils.BitmapUtil;
import com.xps.and.yuntong.Utils.CommonUtils;
import com.xps.and.yuntong.Utils.DensityUtil;
import com.xps.and.yuntong.Utils.FileUtil;
import com.xps.and.yuntong.Utils.MyReceiver;
import com.xps.and.yuntong.View.Custom.WheelView;
import com.xps.and.yuntong.aly.OssService;
import com.xps.and.yuntong.aly.STSGetter;
import com.xps.and.yuntong.aly.UIDisplayer;
import com.xps.and.yuntong.base.BaseActivity;
import com.jude.utils.JUtils;
import com.zhy.base.fileprovider.FileProvider7;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import rx.Subscriber;

/**
 * Created by administrator on 2017-12-09.
 */

public class RegistFourActivity extends BaseActivity implements View.OnClickListener, MyReceiver.Message {
    private static final String[] PLANETS = new String[]{"1", "2", "3", "4", "5", "6"};
    private static final String[] CLColoer = new String[]{"红色", "黄色", "香槟色", "银色", "黑色", "白色", "绿色", "棕色", "灰色", "紫色"};
    private static final String TAG = "RegistFourActivity";
    private static final int REQUEST_DRIVER_LICENSE = 1;//驾驶证
    private static final int REQUEST_DRIVER_ID_FRONT = 2;//正面
    private static final int REQUEST_DRIVER_ID_BACK = 3;//反面
    private static final int REQUEST_DRIVER_ID_BACKXS = 4;//行驶证
    private static final int REQUEST_DRIVER_ID_BAODAN = 5;//保单
    private static final int REQUEST_DRIVER_ID_INfo = 6;//身份信息
    private static int REQUEST_CODE = 0;

    private ImageView iv_fanhui, iv_right, iv_shenfen_zhengmian, iv_shenfen_fanmian, iv_jiashi, iv_xingshi, iv_cheliang_baodan, iv_cheliang_info;
    private LinearLayout ll_shangchuan_zhengmian, ll_shangchuan_fanmian, ll_shangchuan_jianshi, ll_shangchuan_xingshi, ll_shangchuan_cheliang_baodan, ll_shangchuan_cheliang_info, ll_regist_next4;

    private TextView tv_middle, tv_choose_chepai, tv_choose_chexing, tv_choose_chese, tv_choose_cheling;
    private EditText et_choose_chepai, et_choose_chexing, et_choose_chese, et_choose_cheling;
    private ImageView iv_shangchuan_zhengmian, iv_shangchuan_fanmian, iv_shangchuan_jiashi, iv_shangchuan_xingshi, iv_shangchuan_cheliang_baodan, iv_shangchuan_cheliang_info;
    private TextView tv_shangchuan_zhengmian, tv_shangchuan_fanmian, tv_shangchuan_jiashi, tv_shangchuan_xingshi, tv_shangchuan_cheliang_baodan, tv_shangchuan_cheliang_info;


    MyReceiver myReceiver;
    private String panduanxuanze;
    AlertDialog normalDia;

    //图片标记
    int successPicCount = 0;//已经成功的个数
    int actualPicCount = 0;//应该成功的个数
    HashMap<String, ArrayList<String>> data;
    List<String> keyset = new ArrayList<>();

    private String picturePath;
    private String pictureName;
    private String xjxc = "1";

    private OssService ossService;
    private UIDisplayer displayer;


    String name = "";
    String mobile_phone = "";
    String password = "";
    String head_img = "";
    String photo_url = "";
    String idcard_id = "";
    String idcard_up = "";
    String idcard_down = "";
    String driver_license = "";
    String driving_license = "";
    String operatingPermit = "";
    String carPhoto = "";
    String car_id = "";
    String car_color = "";
    String car_type = "";
    String driver_age = "";

    @Override
    protected int getLayout() {
        return R.layout.activity_regist_four;
    }


    @Override
    protected void init(Bundle inBundle) {
        name = JUtils.getSharedPreference().getString("name", "");
        mobile_phone = JUtils.getSharedPreference().getString("mobile_phone", "");
        password = JUtils.getSharedPreference().getString("password", "");
        head_img = JUtils.getSharedPreference().getString("head_img", "");
        photo_url = JUtils.getSharedPreference().getString("photo_url", "");
        idcard_id = JUtils.getSharedPreference().getString("idcard_id", "");


        initView();
//        intDialog();
        initDialog1();
        String headImg = JUtils.getSharedPreference().getString("headImg", "");
        Log.e("headImg", headImg);
    }

    @Override
    protected void setData() {
        displayer = new UIDisplayer(this);
        ossService = initOSS(Constants.endpoint, displayer);
//        ossService.setCallbackAddress(callbackAddress);
        initDiZhi();
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.nangch.broadcasereceiver.MYRECEIVER");
        registerReceiver(myReceiver, intentFilter);
        myReceiver.setMessage(RegistFourActivity.this);
    }

    @Override
    public void photoUploadSuccess() {
        successPicCount++;
        Log.e("111", "已经成功的个数" + successPicCount + "应该成功的个数" + actualPicCount + "photoUploadSuccess");
        if (actualPicCount <= successPicCount) {
            dissmisDialog();
            normalDia.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        displayer = null;
        ossService = null;
    }

    private void initView() {

        iv_fanhui = (ImageView) findViewById(R.id.iv_fanhui);
        iv_right = (ImageView) findViewById(R.id.iv_right);
        iv_right.setVisibility(View.GONE);
        iv_shenfen_zhengmian = (ImageView) findViewById(R.id.iv_shenfen_zhengmian);
        iv_shenfen_fanmian = (ImageView) findViewById(R.id.iv_shenfen_fanmian);
        iv_jiashi = (ImageView) findViewById(R.id.iv_jiashi);
        iv_xingshi = (ImageView) findViewById(R.id.iv_xingshi);
        iv_cheliang_baodan = (ImageView) findViewById(R.id.iv_cheliang_baodan);
        iv_cheliang_info = (ImageView) findViewById(R.id.iv_cheliang_info);
        iv_shangchuan_zhengmian = (ImageView) findViewById(R.id.iv_shangchuan_zhengmian);
        iv_shangchuan_fanmian = (ImageView) findViewById(R.id.iv_shangchuan_fanmian);
        iv_shangchuan_jiashi = (ImageView) findViewById(R.id.iv_shangchuan_jiashi);
        iv_shangchuan_xingshi = (ImageView) findViewById(R.id.iv_shangchuan_xingshi);
        iv_shangchuan_cheliang_baodan = (ImageView) findViewById(R.id.iv_shangchuan_cheliang_baodan);
        iv_shangchuan_cheliang_info = (ImageView) findViewById(R.id.iv_shangchuan_cheliang_info);

        ll_shangchuan_zhengmian = (LinearLayout) findViewById(R.id.ll_shangchuan_zhengmian);
        ll_shangchuan_fanmian = (LinearLayout) findViewById(R.id.ll_shangchuan_fanmian);
        ll_shangchuan_jianshi = (LinearLayout) findViewById(R.id.ll_shangchuan_jianshi);
        ll_shangchuan_xingshi = (LinearLayout) findViewById(R.id.ll_shangchuan_xingshi);
        ll_shangchuan_cheliang_baodan = (LinearLayout) findViewById(R.id.ll_shangchuan_cheliang_baodan);
        ll_shangchuan_cheliang_info = (LinearLayout) findViewById(R.id.ll_shangchuan_cheliang_info);
        ll_regist_next4 = (LinearLayout) findViewById(R.id.ll_regist_next4);

        tv_middle = (TextView) findViewById(R.id.tv_middle);
        tv_middle.setText(R.string.face_recognition);
        tv_choose_chepai = (TextView) findViewById(R.id.tv_choose_chepai);
        tv_choose_chexing = (TextView) findViewById(R.id.tv_choose_chexing);
        tv_choose_chese = (TextView) findViewById(R.id.tv_choose_chese);
        tv_choose_cheling = (TextView) findViewById(R.id.tv_choose_cheling);
        tv_shangchuan_zhengmian = (TextView) findViewById(R.id.tv_shangchuan_zhengmian);
        tv_shangchuan_fanmian = (TextView) findViewById(R.id.tv_shangchuan_fanmian);
        tv_shangchuan_jiashi = (TextView) findViewById(R.id.tv_shangchuan_jiashi);
        tv_shangchuan_xingshi = (TextView) findViewById(R.id.tv_shangchuan_xingshi);
        tv_shangchuan_cheliang_baodan = (TextView) findViewById(R.id.tv_shangchuan_cheliang_baodan);
        tv_shangchuan_cheliang_info = (TextView) findViewById(R.id.tv_shangchuan_cheliang_info);

        et_choose_chepai = (EditText) findViewById(R.id.et_choose_chepai);
        et_choose_chexing = (EditText) findViewById(R.id.et_choose_chexing);
        et_choose_chese = (EditText) findViewById(R.id.et_choose_chese);
        et_choose_cheling = (EditText) findViewById(R.id.et_choose_cheling);


        iv_fanhui.setOnClickListener(this);
        ll_shangchuan_zhengmian.setOnClickListener(this);
        ll_shangchuan_fanmian.setOnClickListener(this);
        ll_shangchuan_jianshi.setOnClickListener(this);
        ll_shangchuan_xingshi.setOnClickListener(this);
        ll_shangchuan_cheliang_baodan.setOnClickListener(this);
        ll_shangchuan_cheliang_info.setOnClickListener(this);
        tv_choose_chepai.setOnClickListener(this);
        tv_choose_chexing.setOnClickListener(this);
        tv_choose_chese.setOnClickListener(this);
        tv_choose_cheling.setOnClickListener(this);
        ll_regist_next4.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.iv_fanhui:

                finish();
                break;

            case R.id.ll_shangchuan_zhengmian:
                REQUEST_CODE = REQUEST_DRIVER_ID_FRONT;

                iv_shangchuan_zhengmian.setVisibility(View.GONE);
                tv_shangchuan_zhengmian.setVisibility(View.GONE);
                iv_shenfen_zhengmian.setVisibility(View.VISIBLE);
                selectDialog();
//                iv_shenfen_zhengmian.setImageResource(R.drawable.just_img);

                break;
            case R.id.ll_shangchuan_fanmian:
                REQUEST_CODE = REQUEST_DRIVER_ID_BACK;
                iv_shangchuan_fanmian.setVisibility(View.GONE);
                tv_shangchuan_fanmian.setVisibility(View.GONE);
                iv_shenfen_fanmian.setVisibility(View.VISIBLE);
                selectDialog();
//                iv_shenfen_fanmian.setImageResource(R.drawable.back_img);
                break;
            case R.id.ll_shangchuan_jianshi:
                REQUEST_CODE = REQUEST_DRIVER_LICENSE;
                iv_shangchuan_jiashi.setVisibility(View.GONE);
                tv_shangchuan_jiashi.setVisibility(View.GONE);
                iv_jiashi.setVisibility(View.VISIBLE);
                selectDialog();
//                iv_jiashi.setImageResource(R.drawable.driving_img);
                break;
            case R.id.ll_shangchuan_xingshi:
                REQUEST_CODE = REQUEST_DRIVER_ID_BACKXS;
//                iv_xingshi.setImageResource(R.drawable.driving_img);
                iv_shangchuan_xingshi.setVisibility(View.GONE);
                tv_shangchuan_xingshi.setVisibility(View.GONE);
                iv_xingshi.setVisibility(View.VISIBLE);
                selectDialog();

                break;
            case R.id.ll_shangchuan_cheliang_info:
                //准运证照片

                REQUEST_CODE = REQUEST_DRIVER_ID_INfo;
                iv_shangchuan_cheliang_info.setVisibility(View.GONE);
                tv_shangchuan_cheliang_info.setVisibility(View.GONE);
                iv_cheliang_info.setVisibility(View.VISIBLE);
                selectDialog();
                break;
            case R.id.ll_shangchuan_cheliang_baodan:

                //车辆正面照片
                REQUEST_CODE = REQUEST_DRIVER_ID_BAODAN;
                iv_shangchuan_cheliang_baodan.setVisibility(View.GONE);
                tv_shangchuan_cheliang_baodan.setVisibility(View.GONE);
                iv_cheliang_baodan.setVisibility(View.VISIBLE);
                selectDialog();
                break;

            case R.id.tv_choose_chepai:

                initCarPlateChooseDialog();
                break;
            case R.id.tv_choose_chexing:
                Intent i = new Intent(RegistFourActivity.this, CarBrandList.class);
                startActivity(i);

                break;
            case R.id.tv_choose_chese:
                panduanxuanze = "CLColoer";
                showCustomizeDialog(CLColoer);

                break;
            case R.id.tv_choose_cheling:
                panduanxuanze = "PLANETS";
                showCustomizeDialog(PLANETS);

                break;
            case R.id.ll_regist_next4:
                if (!ableGoNext()) return;
                if (successPicCount >= actualPicCount) {
                    ll_regist_next4.setEnabled(false);
                    ll_regist_next4.setBackground(getResources().getDrawable(R.drawable.bg_dialog_hui));
                    register();
                } else {
                    showDialogNoCancel();
                    normalDia.show();
                }
                break;

        }
    }


    boolean ableGoNext() {
        if (actualPicCount < 6) {
            JUtils.Toast("请上传全部图片");
            return false;
        }
        if (iv_shenfen_zhengmian.getVisibility() == View.GONE) {
            JUtils.Toast("请上传身份证正面照片");
            return false;
        }
        if (iv_shenfen_fanmian.getVisibility() == View.GONE) {
            JUtils.Toast("请上传身份证反面照片");
            return false;
        }
        if (iv_jiashi.getVisibility() == View.GONE) {
            JUtils.Toast("请上传驾驶证照片");
            return false;
        }
        if (iv_xingshi.getVisibility() == View.GONE) {
            JUtils.Toast("请上传行驶证照片");
            return false;
        }
        if (iv_cheliang_info.getVisibility() == View.GONE) {
            JUtils.Toast("请上传准运证照片");
            return false;
        }
        if (iv_cheliang_baodan.getVisibility() == View.GONE) {
            JUtils.Toast("请上传车辆正面照片");
            return false;
        }
        if (et_choose_chepai.getText().toString().trim().length() != 7) {
            JUtils.Toast("请选择正确车牌号");
            return false;
        }
        if (TextUtils.isEmpty(et_choose_chexing.getText().toString())) {
            JUtils.Toast("请选择车辆品牌");
            return false;
        }
        if (TextUtils.isEmpty(et_choose_chese.getText().toString())) {
            JUtils.Toast("请选择车辆颜色");
            return false;
        }
        if (TextUtils.isEmpty(et_choose_cheling.getText().toString())) {
            JUtils.Toast("请选择车辆车龄");
            return false;
        }
        return true;
    }


    void initCarPlateChooseDialog() {
        View outerView = LayoutInflater.from(RegistFourActivity.this).inflate(R.layout.car_plate_choose_dialog, null);
        final WheelView wv_provence_brief = (WheelView) outerView.findViewById(R.id.wv_provence_brief);
        final WheelView wv_word = (WheelView) outerView.findViewById(R.id.wv_model);
        wv_provence_brief.setOffset(3);
        try {
            wv_provence_brief.setItems(AssetsUitls.getInstance(RegistFourActivity.this).getProvences());
        } catch (IOException e) {
            e.printStackTrace();
        }
        wv_provence_brief.setSeletion(1);
        wv_provence_brief.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                //tv_prov_brief.setText(item);
            }
        });

        wv_word.setOffset(3);
        wv_word.setItems(Arrays.asList(CommonUtils.WORDS));
        wv_word.setSeletion(1);
        new AlertDialog.Builder(RegistFourActivity.this)
                .setTitle("请选择：")
                .setView(outerView)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        et_choose_chepai.setText(wv_provence_brief.getSeletedItem() + wv_word.getSeletedItem());
                        et_choose_chepai.setSelection(et_choose_chepai.length());
                        tv_choose_chepai.setText("    " + wv_provence_brief.getSeletedItem() + " " + wv_word.getSeletedItem() + ":    ");
                    }
                })
                .show();

    }


    @Override
    public void getMsg(String getCouponId) {

        et_choose_chexing.setText(getCouponId);
    }

    public void showCustomizeDialog(String[] PLANETS) {
        View outerView = LayoutInflater.from(RegistFourActivity.this).inflate(R.layout.wheel_view_xin, null);
        WheelView wv = (WheelView) outerView.findViewById(R.id.picker_rel);
        wv.setOffset(2);
        wv.setItems(Arrays.asList(PLANETS));
        wv.setSeletion(0);
        wv.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                if (panduanxuanze.equals("CLColoer")) {
                    et_choose_chese.setText(item);
                } else if (panduanxuanze.equals("PLANETS")) {
                    et_choose_cheling.setText(item);
                }
            }
        });
        wv.onSeletedCallBack();
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(RegistFourActivity.this);
        if (panduanxuanze.equals("CLColoer")) {
            alertDialog.setTitle("选择车辆颜色");
        } else if (panduanxuanze.equals("PLANETS")) {
            alertDialog.setTitle("选择车辆车龄");
        }
        alertDialog.setView(outerView);
        alertDialog.setPositiveButton("确认", null);
        alertDialog.show();
    }

    private void initDialog1() {
        final AlertDialog.Builder normalDialog123 =
                new AlertDialog.Builder(RegistFourActivity.this);
        normalDialog123.setTitle("温馨提示");
        normalDialog123.setMessage("图片正在上传请稍后。。。");
        normalDialog123.setCancelable(false);
        normalDia = normalDialog123.create();

    }

    void selectDialog() {
        final Dialog bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_photo, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(this, 16f);
        params.bottomMargin = DensityUtil.dp2px(this, 8f);
        contentView.setLayoutParams(params);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
        TextView XiCe_pickPhoto = (TextView) contentView.findViewById(R.id.XiCe_pickPhoto);
        XiCe_pickPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xjxc = "1";
                Intent i;
                switch (REQUEST_CODE) {
                    case REQUEST_DRIVER_LICENSE:
                        i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(i, REQUEST_DRIVER_LICENSE);
                        break;
                    case REQUEST_DRIVER_ID_FRONT:
                        i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(i, REQUEST_DRIVER_ID_FRONT);
                        break;
                    case REQUEST_DRIVER_ID_BACK:
                        i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(i, REQUEST_DRIVER_ID_BACK);
                        break;
                    case REQUEST_DRIVER_ID_BACKXS:
                        i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(i, REQUEST_DRIVER_ID_BACKXS);
                        break;
                    case REQUEST_DRIVER_ID_BAODAN:
                        i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(i, REQUEST_DRIVER_ID_BAODAN);
                        break;
                    case REQUEST_DRIVER_ID_INfo:
                        i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(i, REQUEST_DRIVER_ID_INfo);
                        break;
                }
                bottomDialog.dismiss();
            }
        });
        TextView XiJi_takePhoto = (TextView) contentView.findViewById(R.id.XiJi_takePhoto);
        XiJi_takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xjxc = "2";
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                switch (REQUEST_CODE) {
                    case REQUEST_DRIVER_LICENSE:
                        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                            picturePath = "REQUEST_DRIVER_LICENSE.jpg";
                            pictureName = "REQUEST_DRIVER_LICENSE";

                            File file = new File(Environment.getExternalStorageDirectory(), picturePath);
                            picturePath = file.getAbsolutePath();
                            // 仅需改变这一行
                            Uri fileUri = FileProvider7.getUriForFile(RegistFourActivity.this, file);
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                            startActivityForResult(takePictureIntent, REQUEST_DRIVER_LICENSE);
                        }
                        break;
                    case REQUEST_DRIVER_ID_FRONT:
                        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                            picturePath = "REQUEST_DRIVER_ID_FRONT.jpg";
                            pictureName = "REQUEST_DRIVER_ID_FRONT";

                            File file = new File(Environment.getExternalStorageDirectory(), picturePath);
                            picturePath = file.getAbsolutePath();
                            // 仅需改变这一行
                            Uri fileUri = FileProvider7.getUriForFile(RegistFourActivity.this, file);
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                            startActivityForResult(takePictureIntent, REQUEST_DRIVER_ID_FRONT);
                        }
                        break;
                    case REQUEST_DRIVER_ID_BACK:
                        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                            picturePath = "REQUEST_DRIVER_ID_BACK.jpg";
                            pictureName = "REQUEST_DRIVER_ID_BACK";

                            File file = new File(Environment.getExternalStorageDirectory(), picturePath);
                            picturePath = file.getAbsolutePath();
                            // 仅需改变这一行
                            Uri fileUri = FileProvider7.getUriForFile(RegistFourActivity.this, file);
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                            startActivityForResult(takePictureIntent, REQUEST_DRIVER_ID_BACK);
                        }
                        break;
                    case REQUEST_DRIVER_ID_BACKXS:
                        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                            picturePath = "REQUEST_DRIVER_ID_BACKXS.jpg";
                            pictureName = "REQUEST_DRIVER_ID_BACKXS";

                            File file = new File(Environment.getExternalStorageDirectory(), picturePath);
                            picturePath = file.getAbsolutePath();
                            // 仅需改变这一行
                            Uri fileUri = FileProvider7.getUriForFile(RegistFourActivity.this, file);
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                            startActivityForResult(takePictureIntent, REQUEST_DRIVER_ID_BACKXS);
                        }
                        break;
                    case REQUEST_DRIVER_ID_BAODAN:
                        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                            picturePath = "REQUEST_DRIVER_ID_BAODAN.jpg";
                            pictureName = "REQUEST_DRIVER_ID_BAODAN";

                            File file = new File(Environment.getExternalStorageDirectory(), picturePath);
                            picturePath = file.getAbsolutePath();
                            // 仅需改变这一行
                            Uri fileUri = FileProvider7.getUriForFile(RegistFourActivity.this, file);
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                            startActivityForResult(takePictureIntent, REQUEST_DRIVER_ID_BAODAN);
                        }
                        break;
                    case REQUEST_DRIVER_ID_INfo:
                        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                            picturePath = "REQUEST_DRIVER_ID_INfo.jpg";
                            pictureName = "REQUEST_DRIVER_ID_INfo";

                            File file = new File(Environment.getExternalStorageDirectory(), picturePath);
                            picturePath = file.getAbsolutePath();
                            // 仅需改变这一行
                            Uri fileUri = FileProvider7.getUriForFile(RegistFourActivity.this, file);
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                            startActivityForResult(takePictureIntent, REQUEST_DRIVER_ID_INfo);
                        }
                        break;

                }
                bottomDialog.dismiss();
            }
        });

        TextView cancel_TextView = (TextView) contentView.findViewById(R.id.cancel_TextView);
        cancel_TextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });
    }


    void doUploadOSS(String IDBackName) {
        actualPicCount++;
        Log.e("111", "IDBackName" + IDBackName);
        ossService.asyncPutImage(IDBackName, picturePath, mobile_phone);
    }

    void doUploadOSS_v2(String IDBackName) {
        actualPicCount++;
        ossService.asyncPutImage(IDBackName, getProcessedPicFile(pictureName), mobile_phone);
    }

    String getProcessedPicFile(String fileName) {
        String name = fileName + "_PROCESSED.jpg";
        return new File(Environment.getExternalStorageDirectory(), name).getAbsolutePath();
    }

    /**
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (xjxc.equals("1")) {
            if (data == null || resultCode != RESULT_OK) return;
            picturePath = CommonUtils.getRealFilePath(this, data.getData());
            switch (requestCode) {
                case REQUEST_DRIVER_LICENSE:
                    Glide.with(this).load(picturePath).into(iv_jiashi);
                    Log.e("111", "已经成功的个数" + successPicCount + "应该成功的个数" + actualPicCount);
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    Date curDate = new Date(System.currentTimeMillis());
                    String IDBackName = "driverLicense/" + formatter.format(curDate) + "/" + mobile_phone + "/driver.jpg";
                    SharedPreferences sp = JUtils.getSharedPreference();
                    SharedPreferences.Editor spEd = sp.edit();
                    spEd.putString("driver_license", IDBackName);
                    spEd.commit();
                    processBitmapXe("REQUEST_DRIVER_LICENSE.jpg", IDBackName, BitmapUtil.getSmallBitmap(picturePath, 400, 600));
//                  doUploadOSS(IDBackName);
                    break;
                case REQUEST_DRIVER_ID_BACKXS:
                    Glide.with(this).load(picturePath).into(iv_xingshi);
                    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
                    Date curDate1 = new Date(System.currentTimeMillis());
                    String IDBackName1 = "drivingLicense/" + formatter1.format(curDate1) + "/" + mobile_phone + "/driving.jpg";
                    SharedPreferences sp1 = JUtils.getSharedPreference();
                    SharedPreferences.Editor spEd1 = sp1.edit();
                    spEd1.putString("driving_license", IDBackName1);
                    spEd1.commit();
                    processBitmapXe("REQUEST_DRIVER_ID_BACKXS.jpg", IDBackName1, BitmapUtil.getSmallBitmap(picturePath, 400, 600));
//                    doUploadOSS(IDBackName1);
                    break;
                case REQUEST_DRIVER_ID_FRONT:
                    Glide.with(this).load(picturePath).into(iv_shenfen_zhengmian);
                    SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
                    Date curDate2 = new Date(System.currentTimeMillis());
                    String IDBackName2 = "idcard/" + formatter2.format(curDate2) + "/" + mobile_phone + "/up.jpg";
                    SharedPreferences sp2 = JUtils.getSharedPreference();
                    SharedPreferences.Editor spEd2 = sp2.edit();
                    spEd2.putString("idcard_up", IDBackName2);
                    spEd2.commit();
                    processBitmapXe("REQUEST_DRIVER_ID_FRONT.jpg", IDBackName2, BitmapUtil.getSmallBitmap(picturePath, 400, 600));
//                    doUploadOSS(IDBackName2);
                    break;
                case REQUEST_DRIVER_ID_BACK:
                    Glide.with(this).load(picturePath).into(iv_shenfen_fanmian);
                    SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd");
                    Date curDate3 = new Date(System.currentTimeMillis());
                    String IDBackName3 = "idcard/" + formatter3.format(curDate3) + "/" + mobile_phone + "/down.jpg";
                    SharedPreferences sp3 = JUtils.getSharedPreference();
                    SharedPreferences.Editor spEd3 = sp3.edit();
                    spEd3.putString("idcard_down", IDBackName3);
                    spEd3.commit();
                    processBitmapXe("REQUEST_DRIVER_ID_BACK.jpg", IDBackName3, BitmapUtil.getSmallBitmap(picturePath, 400, 600));

//                    doUploadOSS(IDBackName3);
                    break;
                case REQUEST_DRIVER_ID_INfo:
                    //准运证照片
                    Glide.with(this).load(picturePath).into(iv_shangchuan_cheliang_info);
                    SimpleDateFormat formatter4 = new SimpleDateFormat("yyyy-MM-dd");
                    Date curDate4 = new Date(System.currentTimeMillis());
                    String IDBackName4 = "operatingPermit/" + formatter4.format(curDate4) + "/" + mobile_phone + "/op.jpg";
                    SharedPreferences sp4 = JUtils.getSharedPreference();
                    SharedPreferences.Editor spEd4 = sp4.edit();
                    spEd4.putString("operatingPermit", IDBackName4);
                    spEd4.commit();
                    processBitmapXe("REQUEST_DRIVER_ID_INfo.jpg", IDBackName4, BitmapUtil.getSmallBitmap(picturePath, 400, 600));

                    break;
                case REQUEST_DRIVER_ID_BAODAN:
                    Glide.with(this).load(picturePath).into(iv_cheliang_baodan);
                    SimpleDateFormat formatter5 = new SimpleDateFormat("yyyy-MM-dd");
                    Date curDate5 = new Date(System.currentTimeMillis());
                    String IDBackName5 = "carPhoto/" + formatter5.format(curDate5) + "/" + mobile_phone + "/cp.jpg";
                    SharedPreferences sp5 = JUtils.getSharedPreference();
                    SharedPreferences.Editor spEd5 = sp5.edit();
                    spEd5.putString("carPhoto", IDBackName5);
                    spEd5.commit();
                    processBitmapXe("REQUEST_DRIVER_ID_BAODAN.jpg", IDBackName5, BitmapUtil.getSmallBitmap(picturePath, 400, 600));
                    break;
            }
        } else if (xjxc.equals("2")) {
            switch (requestCode) {
                case REQUEST_DRIVER_LICENSE:
                    processBitmap("REQUEST_DRIVER_LICENSE_PROCESSED.jpg", iv_jiashi, BitmapUtil.getSmallBitmap(picturePath, 400, 600));
                    break;
                case REQUEST_DRIVER_ID_BACKXS:
                    processBitmap("REQUEST_DRIVER_ID_BACKXS_PROCESSED.jpg", iv_xingshi, BitmapUtil.getSmallBitmap(picturePath, 400, 600));
                    break;
                case REQUEST_DRIVER_ID_FRONT:
                    processBitmap("REQUEST_DRIVER_ID_FRONT_PROCESSED.jpg", iv_shenfen_zhengmian, BitmapUtil.getSmallBitmap(picturePath, 400, 600));
                    break;
                case REQUEST_DRIVER_ID_BACK:
                    processBitmap("REQUEST_DRIVER_ID_BACK_PROCESSED.jpg", iv_shenfen_fanmian, BitmapUtil.getSmallBitmap(picturePath, 400, 600));
                    break;
                case REQUEST_DRIVER_ID_INfo:
                    processBitmap("REQUEST_DRIVER_ID_INfo_PROCESSED.jpg", iv_cheliang_info, BitmapUtil.getSmallBitmap(picturePath, 400, 600));
                    break;
                case REQUEST_DRIVER_ID_BAODAN:
                    processBitmap("REQUEST_DRIVER_ID_BAODAN_PROCESSED.jpg", iv_cheliang_baodan, BitmapUtil.getSmallBitmap(picturePath, 400, 600));
                    break;
            }
        }
    }


    public OssService initOSS(String endpoint, UIDisplayer displayer) {
        OSSCredentialProvider credentialProvider;
        //使用自己的获取STSToken的类
        if (Constants.stsServer.equals("")) {
            credentialProvider = new STSGetter();
        } else {
            credentialProvider = new STSGetter(Constants.stsServer);
        }

        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(this, endpoint, credentialProvider, conf);
        Log.e("111", "socket连接上了么");
        return new OssService(oss, Constants.bucket, displayer);
    }


    void initDiZhi() {
        try {
            data = AssetsUitls.getInstance(RegistFourActivity.this).getCarBrandMap();
            Iterator<String> i = data.keySet().iterator();
            while (i.hasNext()) {
                keyset.add(i.next());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    void switchLiscenseType() {
        switch (pictureName) {
            case "REQUEST_DRIVER_LICENSE":
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                Date curDate = new Date(System.currentTimeMillis());
                String IDBackName = "driverLicense/" + formatter.format(curDate) + "/" + mobile_phone + "/driver.jpg";

                SharedPreferences sp = JUtils.getSharedPreference();
                SharedPreferences.Editor spEd = sp.edit();
                spEd.putString("driver_license", IDBackName);
                spEd.commit();
                doUploadOSS_v2(IDBackName);
                break;
            case "REQUEST_DRIVER_ID_BACKXS":
                SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
                Date curDate1 = new Date(System.currentTimeMillis());
                String IDBackName1 = "drivingLicense/" + formatter1.format(curDate1) + "/" + mobile_phone + "/driving.jpg";
                SharedPreferences sp1 = JUtils.getSharedPreference();
                SharedPreferences.Editor spEd1 = sp1.edit();
                spEd1.putString("driving_license", IDBackName1);
                spEd1.commit();
                doUploadOSS_v2(IDBackName1);
                break;
            case "REQUEST_DRIVER_ID_FRONT":
                SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
                Date curDate2 = new Date(System.currentTimeMillis());
                String IDBackName2 = "idcard/" + formatter2.format(curDate2) + "/" + mobile_phone + "/up.jpg";
                SharedPreferences sp2 = JUtils.getSharedPreference();
                SharedPreferences.Editor spEd2 = sp2.edit();
                spEd2.putString("idcard_up", IDBackName2);
                spEd2.commit();

                doUploadOSS_v2(IDBackName2);

                break;
            case "REQUEST_DRIVER_ID_BACK":
                SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd");
                Date curDate3 = new Date(System.currentTimeMillis());
                String IDBackName3 = "idcard/" + formatter3.format(curDate3) + "/" + mobile_phone + "/down.jpg";

                SharedPreferences sp3 = JUtils.getSharedPreference();
                SharedPreferences.Editor spEd3 = sp3.edit();
                spEd3.putString("idcard_down", IDBackName3);
                spEd3.commit();
                doUploadOSS_v2(IDBackName3);
                break;
            case "REQUEST_DRIVER_ID_INfo":
                SimpleDateFormat formatter4 = new SimpleDateFormat("yyyy-MM-dd");
                Date curDate4 = new Date(System.currentTimeMillis());
                String IDBackName4 = "operatingPermit/" + formatter4.format(curDate4) + "/" + mobile_phone + "/op.jpg";

                SharedPreferences sp4 = JUtils.getSharedPreference();
                SharedPreferences.Editor spEd4 = sp4.edit();
                spEd4.putString("operatingPermit", IDBackName4);
                spEd4.commit();
                doUploadOSS_v2(IDBackName4);


                break;
            case "REQUEST_DRIVER_ID_BAODAN":
                SimpleDateFormat formatter5 = new SimpleDateFormat("yyyy-MM-dd");
                Date curDate5 = new Date(System.currentTimeMillis());
                String IDBackName5 = "carPhoto/" + formatter5.format(curDate5) + "/" + mobile_phone + "/cp.jpg";

                SharedPreferences sp5 = JUtils.getSharedPreference();
                SharedPreferences.Editor spEd5 = sp5.edit();
                spEd5.putString("carPhoto", IDBackName5);
                spEd5.commit();
                doUploadOSS_v2(IDBackName5);
                break;
        }
    }


    void processBitmap(String name, ImageView iv, Bitmap sourceBitmap) {
        int rotateDegree = FileUtil.getBitmapDegree(picturePath);
        if (rotateDegree != 0) {//如果图片的旋转角度大于0 把角度归零后 重新存储到sd卡 上传
            rx.Observable.just(BitmapUtil.rotateBitmapByDegree(sourceBitmap, 360 - (-rotateDegree)))
                    .subscribeOn(rx.schedulers.Schedulers.io())
                    .doOnNext((b) -> {
                                picturePath = name;
                                File file = new File(Environment.getExternalStorageDirectory(), picturePath);
                                picturePath = file.getAbsolutePath();
                                CommonUtils.saveBitmapToSD(file.getAbsolutePath(), b);
                            }
                    )
                    .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread()).subscribe(new Subscriber<Bitmap>() {
                @Override
                public void onStart() {
                    super.onStart();
                    showDialogNoCancel();
                }

                @Override
                public void onCompleted() {
                    dissmisDialog();
                    switchLiscenseType();
//                    startUpload();
                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                }

                @Override
                public void onNext(Bitmap bitmap) {
                    iv.setImageBitmap(sourceBitmap);
                }
            });
        } else {

//            picturePath = "head.jpg";
            picturePath = name;
            File file = new File(Environment.getExternalStorageDirectory(), picturePath);
            picturePath = file.getAbsolutePath();
            CommonUtils.saveBitmapToSD(file.getAbsolutePath(), sourceBitmap);

            switchLiscenseType();
//            startUpload();
            iv.setImageBitmap(sourceBitmap);
        }
    }


    void processBitmapXe(String name, String IDBackName, Bitmap sourceBitmap) {
        int rotateDegree = FileUtil.getBitmapDegree(picturePath);
        if (rotateDegree != 0) {//如果图片的旋转角度大于0 把角度归零后 重新存储到sd卡 上传
            rx.Observable.just(BitmapUtil.rotateBitmapByDegree(sourceBitmap, 360 - (-rotateDegree)))
                    .subscribeOn(rx.schedulers.Schedulers.io())
                    .doOnNext((b) -> {
                                picturePath = name;
                                File file = new File(Environment.getExternalStorageDirectory(), picturePath);
                                picturePath = file.getAbsolutePath();
                                CommonUtils.saveBitmapToSD(picturePath, b);
                                JUtils.Log("doOnNext");
                            }
                    )
                    .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread()).subscribe(new Subscriber<Bitmap>() {
                @Override
                public void onStart() {
                    super.onStart();
                    showDialogNoCancel();
                }

                @Override
                public void onCompleted() {
                    dissmisDialog();
                    doUploadOSS(IDBackName);
//                    switchLiscenseType();
//                    startUpload();
                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                }

                @Override
                public void onNext(Bitmap bitmap) {
//                    iv.setImageBitmap(sourceBitmap);
                }
            });
        } else {

            Log.e("111", "IDBackName");
            picturePath = name;
            File file = new File(Environment.getExternalStorageDirectory(), picturePath);
            picturePath = file.getAbsolutePath();
            CommonUtils.saveBitmapToSD(file.getAbsolutePath(), sourceBitmap);
            doUploadOSS(IDBackName);
//            switchLiscenseType();
//            startUpload();
//            iv.setImageBitmap(sourceBitmap);
        }
    }

    private void register() {

        idcard_up = JUtils.getSharedPreference().getString("idcard_up", "");
        idcard_down = JUtils.getSharedPreference().getString("idcard_down", "");
        driver_license = JUtils.getSharedPreference().getString("driver_license", "");
        driving_license = JUtils.getSharedPreference().getString("driving_license", "");
        operatingPermit = JUtils.getSharedPreference().getString("operatingPermit", "");
        carPhoto = JUtils.getSharedPreference().getString("carPhoto", "");
        car_id = et_choose_chepai.getText().toString().trim();
        car_color = et_choose_chese.getText().toString().trim();
        car_type = et_choose_chexing.getText().toString().trim();
        driver_age = et_choose_cheling.getText().toString().trim();

        Log.e("111", "name" + name + "mobile_phone" + mobile_phone + "password" + password + "head_img" + head_img + "photo_url" + photo_url);
        Log.e("111", "idcard_id" + idcard_id + "idcard_up" + idcard_up + "idcard_up" + password + "idcard_up" + head_img + "driver_license" + driver_license);
        Log.e("111", "driving_license" + driving_license + "car_id" + car_id + "driver_age" + driver_age);
        UserNetWorks.getRegister(name, mobile_phone, password, head_img, photo_url, idcard_id, idcard_up, idcard_down, driver_license, driving_license, operatingPermit, car_id, car_color, car_type, carPhoto, driver_age, new Subscriber<doRegister>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                JUtils.Toast("发送失败");
                ll_regist_next4.setEnabled(true);
                ll_regist_next4.setBackground(getResources().getDrawable(R.drawable.bg_dialog_lan));
            }

            @Override
            public void onNext(doRegister doRegister) {
                if (doRegister.getReturn_code().equals("SUCCESS")) {
//                    JUtils.Toast(doRegister.getReturn_msg());
                    JUtils.Toast("已提交注册,请等待审核!");
                    ll_regist_next4.setEnabled(true);
                    ll_regist_next4.setBackground(getResources().getDrawable(R.drawable.bg_dialog_lan));
                    Intent intent = new Intent(RegistFourActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                    AppCommond appCommond = new AppCommond.Builder()
                            .setOpration(AppCommond.CLOSE_ACTIVITY)
                            .setRequestcloseAcname(RegistThreeActivity.class.getSimpleName(), RegistTwoCeshiActivity.class.getSimpleName(), RegistOneActivity.class.getSimpleName())
                            .build();
                    EventBus.getDefault().post(appCommond);
                } else if (doRegister.getReturn_code().equals("FAIL")) {
                    JUtils.Toast(doRegister.getReturn_msg());
                    ll_regist_next4.setEnabled(true);
                    ll_regist_next4.setBackground(getResources().getDrawable(R.drawable.bg_dialog_lan));
                }

            }
        });
    }

}
